/**
 * Created by callmesoul on 2017/4/10.
 */
// var jwt = require('jsonwebtoken');
var Oauth = require('co-wechat-oauth');
module.exports = (options,app) => {
    return async function (ctx,next) {
        if(ctx.request.query && (ctx.request.query.wpid || (ctx.request.body && ctx.request.body.wpid))){
            const wpid=ctx.request.query.wpid ? ctx.request.query.wpid : ctx.request.body.wpid;
            var wp = await ctx.model.Wechat.findById(wpid);
            const now =new Date().getTime();
            wp.accessToken=wp.accessToken?JSON.parse(wp.accessToken):wp.accessToken;
            if(!wp.accessToken || !(wp.accessToken.expireTime<now)){//没有或accesstoken过期
                var result=await ctx.curl('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+wp.appId+'&secret='+wp.appSecret,{dataType: 'json'});
                var accessToken={
                    accessToken:result.data.access_token,
                    expireTime:now+result.data.expires_in
                };

                accessToken=JSON.stringify(accessToken);
                wp.accessToken=accessToken;
                wp.save();
                wp.accessToken=JSON.parse(wp.accessToken);
            }
            ctx.wechat=wp;

            await next();
        }else {
            await next();
        }

    };
};
